package com.lvmama.rhino.web;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.lvmama.entity.system.SysUser;
import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.entity.H5RuleVO;
import com.lvmama.rhino.entity.H5pageMonitorVO;
import com.lvmama.rhino.entity.PageMonitorVO;
import com.lvmama.rhino.entity.SignParamInfo;
import com.lvmama.rhino.enums.CommonStringType;
import com.lvmama.rhino.pojo.*;
import com.lvmama.rhino.service.PageMonitorService;
import com.lvmama.rhino.service.impl.ElasticsearchDataService;
import com.lvmama.rhino.service.impl.ElasticsearchIndexService;
import com.lvmama.rhino.utils.Constants;
import com.lvmama.rhino.utils.DateUtil;
import com.lvmama.rhino.utils.ExportCSVUtils;
import com.lvmama.rhino.utils.ExportExcelUtils;
import com.lvmama.rhino.web.sso.SystemSession;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.elasticsearch.search.sort.SortOrder;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("webStatistics")
public class WebStatisticsController extends BaseControllerSupport {

    @Autowired
    private PageMonitorService pageMonitorService;

    @Autowired
    private ElasticsearchIndexService service;

    @RequestMapping("firstScreenTime")
    public String firstScreenTime(ModelMap model, PageMonitorVO pageMonitorVO) throws Exception {
        pageMonitorVO = queryPageMonitorVO(pageMonitorVO);//获取页面上的查询条件
        long start = pageMonitorVO.getStart_date().getTime();//开始时间
        long end = pageMonitorVO.getEnd_date().getTime();//结束时间
        //PageInfo<PageMonitor> page = pageMonitorService.queryPageMonitorList(pageMonitorVO);//根据条件分页查询
        PageInfo<PageMonitorInfo> page = new PageInfo<PageMonitorInfo>();
        int pageNum = pageMonitorVO.getPage();//当前页数
        int pageSize = pageMonitorVO.getPageSize();//页面大小
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        int startRow = (pageNum - 1) * pageSize + 1;//开始条数
        page.setStartRow(startRow);
        page.setEndRow(pageNum * pageSize);//结束条数
        page.setFirstPage(1);
        page.setPrePage(pageNum - 1);//上一页
        page.setNextPage(pageNum + 1);//下一页
        /*ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:elasticsearch.xml");  
        ElasticsearchDataService service =  (ElasticsearchDataService)context.getBean("es");*/
        ElasticsearchDataService service = new ElasticsearchDataService();
        String url = pageMonitorVO.getUrl() != null ? pageMonitorVO.getUrl() : "*";//模糊查询的url
        pageMonitorVO.setUrl(url);
        long totalDataCountAll = service.dataCount(Constants.H5Page_TYPE_NAME_ALL, "visit_times", start, end, url);//全部时段数据总数
        Long totalDataCount1 = service.dataCount(Constants.H5Page_TYPE_NAME_Period_1, "visit_times", start, end, url);//0s-1s数据总数
        Long totalDataCount2 = service.dataCount(Constants.H5Page_TYPE_NAME_Period_2, "visit_times", start, end, url);//1s-2s数据总数
        Long totalDataCount3 = service.dataCount(Constants.H5Page_TYPE_NAME_Period_3, "visit_times", start, end, url);//2s-3s数据总数
        Long totalDataCount4 = service.dataCount(Constants.H5Page_TYPE_NAME_Period_4, "visit_times", start, end, url);//3s-5s数据总数
        Long totalDataCount5 = service.dataCount(Constants.H5Page_TYPE_NAME_Period_5, "visit_times", start, end, url);//5s以上数据总数
        String timeInterval = pageMonitorVO.getTimeInterval();//查询时段
        String typeName = null;
        long totalDataCount = 0l;
        /*判断获取es索引的类型*/
        if ("0s-1s".equals(timeInterval)) {
            typeName = "h5_page_monitor_1";
            totalDataCount = totalDataCount1;
        } else if ("1s-2s".equals(timeInterval)) {
            typeName = "h5_page_monitor_2";
            totalDataCount = totalDataCount2;
        } else if ("2s-3s".equals(timeInterval)) {
            typeName = "h5_page_monitor_3";
            totalDataCount = totalDataCount3;
        } else if ("3s-5s".equals(timeInterval)) {
            typeName = "h5_page_monitor_4";
            totalDataCount = totalDataCount4;
        } else if ("5s以上".equals(timeInterval)) {
            typeName = "h5_page_monitor_5";
            totalDataCount = totalDataCount5;
        } else {
            typeName = "h5_page_monitor";
            totalDataCount = totalDataCountAll;
        }

        //查询分组后的数据
        List<Map<String, Object>> al = service.AggregationData(typeName, "average_time", SortOrder.DESC, start, end, url);
        List<PageMonitor> list = new ArrayList<PageMonitor>();
        //将查询到数据封装到数组中
        for (Map<String, Object> map : al) {
            PageMonitor pm = new PageMonitor();
            pm.setProvince(map.get("province") != null ? map.get("province").toString() : null);
            pm.setCity(map.get("city") != null ? map.get("city").toString() : null);
            pm.setOperators(map.get("operators") != null ? map.get("operators").toString() : null);
            //pm.setCategory_id(map.get("category_id") != null ? map.get("category_id").toString() : null);
            pm.setNetwork_type(map.get("network_type") != null ? map.get("network_type").toString() : null);
            //pm.setLoad_time(map.get("load_time") != null ? (Double)map.get("load_time") : null);
            pm.setTotal_load_time(map.get("total_load_time") != null ? (Double) map.get("total_load_time") : null);
            //pm.setIs_lv(map.get("is_lv") != null ? map.get("is_lv").toString() : null);
            //pm.setCreate_date(map.get("create_date") != null ? (Date)map.get("create_date") : null);
            pm.setVisit_times(map.get("visit_times") != null ? Long.valueOf(map.get("visit_times").toString()) : null);
            //pm.setProportion(map.get("proportion") != null ? map.get("proportion").toString() : null);
            //pm.setAverage_time(map.get("average_time") != null ? (Double)map.get("average_time") : null);
            //pm.setAverage_time_str(map.get("average_time_str") != null ? map.get("average_time_str").toString() : null);
            //pm.setPage_code(map.get("page_code") != null ? map.get("page_code").toString() : null);
            list.add(pm);
        }

        String paramsAll = "province,city,operators,network_type";
        String params = pageMonitorVO.getSignParams();
        if (params == null || "".equals(params)) {
            params = paramsAll;
        } else {
            params = pageMonitorVO.getSignParams();
        }
        //String params = pageMonitorVO.getSignParams() != null?pageMonitorVO.getSignParams():paramsAll;
        String[] keys = params.split(",");
        List<String> keysList = Arrays.asList(keys);
        List<SignParamInfo> signParamInfoList = getSignParamInfoList(params);

        //数据根据维度进行分组
        List<PageMonitor> newList = new ArrayList<PageMonitor>();
        for (PageMonitor pm : list) {
            boolean flag = false;
            String key = "";
            if (keysList.contains("province")) {
                key += pm.getProvince();
            }
            if (keysList.contains("city")) {
                key += pm.getCity();
            }
            if (keysList.contains("operators")) {
                key += pm.getOperators();
            }
            if (keysList.contains("network_type")) {
                key += pm.getNetwork_type();
            }
            //key = pm.getProvince() + "," + pm.getCity() + "," + pm.getOperators() + "," + pm.getNetwork_type();
            for (PageMonitor newPm : newList) {
                String newKey = "";
                if (keysList.contains("province")) {
                    newKey += newPm.getProvince();
                }
                if (keysList.contains("city")) {
                    newKey += newPm.getCity();
                }
                if (keysList.contains("operators")) {
                    newKey += newPm.getOperators();
                }
                if (keysList.contains("network_type")) {
                    newKey += newPm.getNetwork_type();
                }
                //String newKey = newPm.getProvince() + "," + newPm.getCity() + "," + newPm.getOperators() + "," + newPm.getNetwork_type();
                if (key.equals(newKey)) {
                    Double total_load_time = newPm.getTotal_load_time();
                    Long visit_times = newPm.getVisit_times();
                    total_load_time += pm.getTotal_load_time();
                    visit_times += pm.getVisit_times();
                    newPm.setTotal_load_time(total_load_time);
                    newPm.setVisit_times(visit_times);
                    flag = true;
                }
            }
            if (!flag) {
                newList.add(pm);
            }
        }
        //数据总量
        int dataCount = newList.size();
        page.setTotal(dataCount);
        int add = dataCount % pageSize == 0 ? 0 : 1;
        int sum = dataCount / pageSize + add;
        page.setPages(sum);
        page.setLastPage(sum);

        //根据平均时间降序排序
        Collections.sort(newList, new Comparator<PageMonitor>() {
            @Override
            public int compare(PageMonitor o1, PageMonitor o2) {
                return o1.getTotal_load_time() / o1.getVisit_times() >= o2.getTotal_load_time() / o2.getVisit_times() ? -1 : 1;
            }
        });
        List<PageMonitor> pageMonitorList = new ArrayList<PageMonitor>();
        //截取页面展示的数据
        int right = startRow + pageSize - 1;
        if (newList != null && newList.size() != 0) {
            if (right > dataCount) {
                right = dataCount;
            }
            pageMonitorList = new ArrayList<PageMonitor>(newList.subList(startRow - 1, right));
        }

        //Integer count = pageMonitorService.queryPageMonitorListCount(pageMonitorVO);//根据条件查询总的访问次数
        DecimalFormat df = new DecimalFormat("#0.000");
        DecimalFormat df1 = new DecimalFormat("#0.00");

        for (PageMonitor pageMonitor : pageMonitorList) {
            //set平均时间
            String average_time = df.format(pageMonitor.getTotal_load_time() / pageMonitor.getVisit_times());
            pageMonitor.setAverage_time_str(average_time);
            //set占比
            String proportion = df1.format((pageMonitor.getVisit_times().doubleValue() / totalDataCount) * 100) + "%";
            pageMonitor.setProportion(proportion);
        }

        //通过枚举获得品类的信息
        CommonStringType[] getH5PageMonitorProduct = CommonStringType.getH5PageCodeType();
        List<CommonStringType> h5PageMonitorProductList = Arrays.asList(getH5PageMonitorProduct);
        model.addAttribute("page", page);
        model.addAttribute("pageMonitors", pageMonitorList);
        model.addAttribute("pageMonitorVO", pageMonitorVO);
        model.addAttribute("h5PageMonitorProductList", h5PageMonitorProductList);
        model.addAttribute("signParamInfoList", signParamInfoList);
        SysUser user = SystemSession.getUser();
        model.addAttribute("currentUser", user);//当前用户

        DecimalFormat df2 = new DecimalFormat("#0.00");
        List<Double> proportionList = new ArrayList<Double>();
        //求出耗时范围内的首屏时间的耗时占比
        String proportion1Str = "0";
        String proportion2Str = "0";
        String proportion3Str = "0";
        String proportion4Str = "0";
        String proportion5Str = "0";
        if (totalDataCount != 0) {
            proportion1Str = df2.format((totalDataCount1.doubleValue() / totalDataCountAll) * 100);
            proportion2Str = df2.format((totalDataCount2.doubleValue() / totalDataCountAll) * 100);
            proportion3Str = df2.format((totalDataCount3.doubleValue() / totalDataCountAll) * 100);
            proportion4Str = df2.format((totalDataCount4.doubleValue() / totalDataCountAll) * 100);
            proportion5Str = df2.format((totalDataCount5.doubleValue() / totalDataCountAll) * 100);
        }
        Double proportion1 = Double.parseDouble(proportion1Str);
        Double proportion2 = Double.parseDouble(proportion2Str);
        Double proportion3 = Double.parseDouble(proportion3Str);
        Double proportion4 = Double.parseDouble(proportion4Str);
        Double proportion5 = Double.parseDouble(proportion5Str);
        proportionList.add(proportion1);
        proportionList.add(proportion2);
        proportionList.add(proportion3);
        proportionList.add(proportion4);
        proportionList.add(proportion5);
        String proportionListStr = proportion1 + ", " + proportion2 + "," + proportion3 + "," + proportion4 + "," + proportion5;
        model.addAttribute("proportionListData", proportionListStr);

        return "application/firstScreenTimeList";
    }

    @RequestMapping("ajaxJob")
    @ResponseBody
    public Map<String, Object> ajaxJob() {
        Date date = new Date();
        String dateStr = DateUtil.getStrDayOfMonth(date, 7, "yyyyMMdd");
        String result = pageMonitorService.queryPartition("part_" + dateStr);
        if (result == null) {
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("dateStr", "part_" + dateStr);
            param.put("str", "'" + dateStr + "'");
            pageMonitorService.createPartition(param);
            logger.info("新建part_" + dateStr + "分区成功");
        } else {
            logger.info("part_" + dateStr + "分区已存在");
        }
        logger.info("h5首屏时间手动启动任务");
        PageMonitorVO pageMonitorVO = getPageMonitorVO();//返回前七天的日期
        //PageMonitorMapper pageMonitorMapper = applicationContext.getBean(PageMonitorMapper.class);
        //List<PageMonitor> pageMonitorList = pageMonitorService.queryTimePageMonitorList(pageMonitorVO);//根据条件查询所有数据信息
        //根据条件查询加载时段为0s-1s所有数据信息
        List<PageMonitorInfo> pageMonitorInfoList = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        pageMonitorVO.setMinTime(0.0);
        pageMonitorVO.setMaxTime(1.0);
        //根据条件查询加载时段为1s-2s所有数据信息
        List<PageMonitorInfo> pageMonitorInfoList1 = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        pageMonitorVO.setMinTime(1.0);
        pageMonitorVO.setMaxTime(2.0);
        //根据条件查询加载时段为2s-3s所有数据信息
        List<PageMonitorInfo> pageMonitorInfoList2 = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        pageMonitorVO.setMinTime(2.0);
        pageMonitorVO.setMaxTime(3.0);
        //根据条件查询加载时段为3s-5s所有数据信息
        List<PageMonitorInfo> pageMonitorInfoList3 = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        pageMonitorVO.setMinTime(3.0);
        pageMonitorVO.setMaxTime(5.0);
        //根据条件查询加载时段为5s以上所有数据信息
        List<PageMonitorInfo> pageMonitorInfoList4 = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        pageMonitorVO.setMinTime(5.0);
        pageMonitorVO.setMaxTime(null);
        List<PageMonitorInfo> pageMonitorInfoList5 = pageMonitorService.getMessageInfoListPage(pageMonitorVO);
        /*ClassPathXmlApplicationContext context1 = new ClassPathXmlApplicationContext("classpath:elasticsearch.xml");  
        ElasticsearchIndexService service = context1.getBean(ElasticsearchIndexService.class);  */
        ElasticsearchIndexService services = new ElasticsearchIndexService();
        //删除rhino索引
        services.deleteIndex(Constants.H5Page_INDEX_NAME);
        try {
            //创建rhino索引下的h5_page_monitor类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_ALL);
            //创建rhino索引下的h5_page_monitor_1类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_1);
            //创建rhino索引下的h5_page_monitor_2类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_2);
            //创建rhino索引下的h5_page_monitor_3类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_3);
            //创建rhino索引下的h5_page_monitor_4类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_4);
            //创建rhino索引下的h5_page_monitor_5类型
            service.create(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_5);
        } catch (IOException e) {
            e.printStackTrace();
        }
        boolean insert = false;
        boolean insert1 = false;
        boolean insert2 = false;
        boolean insert3 = false;
        boolean insert4 = false;
        boolean insert5 = false;
        if (pageMonitorInfoList != null && pageMonitorInfoList.size() != 0) {
            //在rhino索引下的h5_page_monitor类型批量插入数据
            insert = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_ALL, pageMonitorInfoList);
            logger.info("在rhino索引下的h5_page_monitor类型批量插入数据:" + insert);
        }
        if (pageMonitorInfoList1 != null && pageMonitorInfoList1.size() != 0) {
            //在rhino索引下的h5_page_monitor_1类型批量插入数据
            insert1 = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_1, pageMonitorInfoList1);
            logger.info("在rhino索引下的h5_page_monitor_1类型批量插入数据:" + insert1);
        }
        if (pageMonitorInfoList2 != null && pageMonitorInfoList2.size() != 0) {
            //在rhino索引下的h5_page_monitor_2类型批量插入数据
            insert2 = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_2, pageMonitorInfoList2);
            logger.info("在rhino索引下的h5_page_monitor_2类型批量插入数据:" + insert2);
        }
        if (pageMonitorInfoList3 != null && pageMonitorInfoList3.size() != 0) {
            //在rhino索引下的h5_page_monitor_3类型批量插入数据
            insert3 = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_3, pageMonitorInfoList3);
            logger.info("在rhino索引下的h5_page_monitor_3类型批量插入数据:" + insert3);
        }
        if (pageMonitorInfoList4 != null && pageMonitorInfoList4.size() != 0) {
            //在rhino索引下的h5_page_monitor_4类型批量插入数据
            insert4 = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_4, pageMonitorInfoList4);
            logger.info("在rhino索引下的h5_page_monitor_4类型批量插入数据:" + insert4);
        }
        if (pageMonitorInfoList5 != null && pageMonitorInfoList5.size() != 0) {
            //在rhino索引下的h5_page_monitor_5类型批量插入数据
            insert5 = service.insertOrUpdatePageMonitorInfo(Constants.H5Page_INDEX_NAME, Constants.H5Page_TYPE_NAME_Period_5, pageMonitorInfoList5);
            logger.info("在rhino索引下的h5_page_monitor_5类型批量插入数据:" + insert5);
        }
        Map<String, Object> map = new HashMap<String, Object>();
        if (insert && insert1 && insert2 && insert3 && insert4 && insert5) {
            map.put("message", "批量插入数据成功");
        } else {
            map.put("message", "批量插入数据失败");
        }
        return map;
    }

    /**
     * 返回前七天日期
     *
     * @return
     */
    public PageMonitorVO getPageMonitorVO() {
        Date date0 = new Date();
        SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
        Calendar calendar1 = new GregorianCalendar();
        calendar1.setTime(date0);
        calendar1.add(calendar1.DATE, -1);
        Date date1 = calendar1.getTime();
        String dateStr1 = formatter1.format(date1);
        calendar1.add(calendar1.DATE, -6);
        date1 = calendar1.getTime();
        String dateStr2 = formatter1.format(date1);
        String dateStr = dateStr2 + " - " + dateStr1;
        PageMonitorVO pageMonitorVO = new PageMonitorVO();
        pageMonitorVO.setChooseTimeVO(dateStr);
        if (pageMonitorVO.getChooseTimeVO() != null) {
            String[] split = pageMonitorVO.getChooseTimeVO().split("-");
            DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
            Date startDate = DateTime.parse(split[0].trim() + " 00:00:00", formater).toDate();
            Date endDate = DateTime.parse(split[1].trim() + " 23:59:59", formater).toDate();
            pageMonitorVO.setStart_date(startDate);
            pageMonitorVO.setEnd_date(endDate);
        } else {
            pageMonitorVO.setStart_date(null);
            pageMonitorVO.setEnd_date(null);
        }
        return pageMonitorVO;
    }


    /**
     * 通过ajax从后台获取消息回执数量信息
     *
     * @return
     */
    @RequestMapping("ajaxData")
    @ResponseBody
    public Map<String, Object> ajaxData(PageMonitorVO pageMonitorVO) {
        //根据选择时段获取开始时间和结束时间
        if (pageMonitorVO.getChooseTimeVO() != null) {
            String[] split = pageMonitorVO.getChooseTimeVO().split("-");
            DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
            Date startDate = DateTime.parse(split[0].trim() + " 00:00:00", formater).toDate();
            Date endDate = DateTime.parse(split[1].trim() + " 23:59:59", formater).toDate();
            pageMonitorVO.setStart_date(startDate);
            pageMonitorVO.setEnd_date(endDate);
        } else {
            pageMonitorVO.setStart_date(null);
            pageMonitorVO.setEnd_date(null);
        }
        List<PageMonitor> pageMonitorList = pageMonitorService.queryTimePageMonitorList(pageMonitorVO);//根据条件查询所有数据信息
        Long option1 = 0l;
        Long option2 = 0l;
        Long option3 = 0l;
        Long option4 = 0l;
        Long option5 = 0l;
        //遍历数据划分时段
        for (PageMonitor pageMonitor : pageMonitorList) {
            Double loadtime = pageMonitor.getLoad_time();
            if (loadtime <= 1 && loadtime > 0) {
                option1++;
            } else if (loadtime <= 2 && loadtime > 1) {
                option2++;
            } else if (loadtime <= 3 && loadtime > 2) {
                option3++;
            } else if (loadtime <= 5 && loadtime > 3) {
                option4++;
            } else if (loadtime > 5) {
                option5++;
            }
        }
        DecimalFormat df1 = new DecimalFormat("#0.00");
        List<Double> proportionList = new ArrayList<Double>();
        int count = pageMonitorList.size();
        //求出耗时范围内的首屏时间的耗时占比
        String proportion1Str = df1.format((option1.doubleValue() / count) * 100);
        String proportion2Str = df1.format((option2.doubleValue() / count) * 100);
        String proportion3Str = df1.format((option3.doubleValue() / count) * 100);
        String proportion4Str = df1.format((option4.doubleValue() / count) * 100);
        String proportion5Str = df1.format((option5.doubleValue() / count) * 100);
        Double proportion1 = Double.parseDouble(proportion1Str);
        Double proportion2 = Double.parseDouble(proportion2Str);
        Double proportion3 = Double.parseDouble(proportion3Str);
        Double proportion4 = Double.parseDouble(proportion4Str);
        Double proportion5 = Double.parseDouble(proportion5Str);
        proportionList.add(proportion1);
        proportionList.add(proportion2);
        proportionList.add(proportion3);
        proportionList.add(proportion4);
        proportionList.add(proportion5);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("proportionListData", proportionList);
        return map;
    }


    /**
     * 导出首屏时间的信息
     *
     * @param pageMonitorVO
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping("export")
    public void exportData(PageMonitorVO pageMonitorVO, HttpServletResponse response, HttpServletRequest request) throws IOException {
        pageMonitorVO = queryPageMonitorVO(pageMonitorVO);//获取页面上的查询条件
        long start = pageMonitorVO.getStart_date().getTime();//开始时间
        long end = pageMonitorVO.getEnd_date().getTime();//结束时间
        String timeInterval = pageMonitorVO.getTimeInterval();//耗时范围
        String typeName = null;
        //判断获取索引的类型
        if ("0s-1s".equals(timeInterval)) {
            typeName = "h5_page_monitor_1";
        } else if ("1s-2s".equals(timeInterval)) {
            typeName = "h5_page_monitor_2";
        } else if ("2s-3s".equals(timeInterval)) {
            typeName = "h5_page_monitor_3";
        } else if ("3s-5s".equals(timeInterval)) {
            typeName = "h5_page_monitor_4";
        } else if ("5s以上".equals(timeInterval)) {
            typeName = "h5_page_monitor_5";
        } else {
            typeName = "h5_page_monitor";
        }
        ElasticsearchDataService service = new ElasticsearchDataService();
        String url = pageMonitorVO.getUrl() != null ? pageMonitorVO.getUrl() : "";//模糊查询的url
        //查询符合条件的数据总量
        long count = service.dataCount(typeName, "visit_times", start, end, url);
        //查询符合条件的分组的数据
        List<Map<String, Object>> al = service.AggregationData(typeName, "average_time", SortOrder.DESC, start, end, url);
        int dataCount = al.size();
        List<PageMonitor> list = new ArrayList<PageMonitor>();
        //map中的值封装到对象中
        for (Map<String, Object> map : al) {
            PageMonitor pm = new PageMonitor();
            pm.setProvince(map.get("province") != null ? map.get("province").toString() : null);
            pm.setCity(map.get("city") != null ? map.get("city").toString() : null);
            pm.setOperators(map.get("operators") != null ? map.get("operators").toString() : null);
            pm.setNetwork_type(map.get("network_type") != null ? map.get("network_type").toString() : null);
            pm.setTotal_load_time(map.get("total_load_time") != null ? (Double) map.get("total_load_time") : null);
            pm.setVisit_times(map.get("visit_times") != null ? Long.valueOf(map.get("visit_times").toString()) : null);
            list.add(pm);
        }

        String paramsAll = "province,city,operators,network_type";
        //明细表维度
        String params = pageMonitorVO.getSignParams();
        if (params == null || "".equals(params)) {
            params = paramsAll;
        } else {
            params = pageMonitorVO.getSignParams();
        }
        //String params = pageMonitorVO.getSignParams() != null?pageMonitorVO.getSignParams():paramsAll;
        String[] keys = params.split(",");
        List<String> keysList = Arrays.asList(keys);

        //数据根据维度进行分组
        //分组操作后的数据
        List<PageMonitor> newList = new ArrayList<PageMonitor>();
        for (PageMonitor pm : list) {
            boolean flag = false;
            String key = "";
            if (keysList.contains("province")) {
                key += pm.getProvince();
            }
            if (keysList.contains("city")) {
                key += pm.getCity();
            }
            if (keysList.contains("operators")) {
                key += pm.getOperators();
            }
            if (keysList.contains("network_type")) {
                key += pm.getNetwork_type();
            }
            //key = pm.getProvince() + "," + pm.getCity() + "," + pm.getOperators() + "," + pm.getNetwork_type();
            for (PageMonitor newPm : newList) {
                String newKey = "";
                if (keysList.contains("province")) {
                    newKey += newPm.getProvince();
                }
                if (keysList.contains("city")) {
                    newKey += newPm.getCity();
                }
                if (keysList.contains("operators")) {
                    newKey += newPm.getOperators();
                }
                if (keysList.contains("network_type")) {
                    newKey += newPm.getNetwork_type();
                }
                //String newKey = newPm.getProvince() + "," + newPm.getCity() + "," + newPm.getOperators() + "," + newPm.getNetwork_type();
                if (key.equals(newKey)) {
                    Double total_load_time = newPm.getTotal_load_time();
                    Long visit_times = newPm.getVisit_times();
                    total_load_time += pm.getTotal_load_time();
                    visit_times += pm.getVisit_times();
                    newPm.setTotal_load_time(total_load_time);
                    newPm.setVisit_times(visit_times);
                    flag = true;
                }
            }
            if (!flag) {
                newList.add(pm);
            }
        }
        //List<PageMonitor> list = pageMonitorService.queryExportPageMonitorList(pageMonitorVO);//根据条件查询需要导出的数据
        //Integer count = pageMonitorService.queryPageMonitorListCount(pageMonitorVO);//根据条件查询总的访问次数

        DecimalFormat df = new DecimalFormat("#0.000");
        DecimalFormat df1 = new DecimalFormat("#0.00");

        for (PageMonitor pageMonitor : newList) {
            //set平均时间
            String average_time = df.format(pageMonitor.getTotal_load_time() / pageMonitor.getVisit_times());
            pageMonitor.setAverage_time_str(average_time);
            //set占比
            String proportion = df1.format((pageMonitor.getVisit_times().doubleValue() / count) * 100) + "%";
            pageMonitor.setProportion(proportion);
        }

        //根据平均时间降序排序
        Collections.sort(newList, new Comparator<PageMonitor>() {
            @Override
            public int compare(PageMonitor o1, PageMonitor o2) {
                return o1.getTotal_load_time() / o1.getVisit_times() >= o2.getTotal_load_time() / o2.getVisit_times() ? -1 : 1;
            }
        });

        ExportExcelUtils ex = new ExportExcelUtils();
        //String[] headers = new String[]{ "省份", "城市", "运营商", "网络制式" , "平均时间(s)" , "访问次数" , "占比"};
        String[] addTitle = new String[]{"平均时间(s)", "访问次数", "占比"};
        List<SignParamInfo> signParamInfoList = getSignParamInfoList(params);
        String paramsName = "";
        for (SignParamInfo signParamInfo : signParamInfoList) {
            if (signParamInfo.isChecked()) {
                paramsName += signParamInfo.getShowName() + ",";
            }
        }
        paramsName = paramsName.substring(0, paramsName.length() - 1);
        String[] optionalTitle = paramsName.split(",");
        //合并两个数组
        String[] headers = (String[]) ArrayUtils.addAll(optionalTitle, addTitle);

        //String category_id = CommonParentType.getH5PageMonitorProductShowName(pageMonitorVO.getCategory_id());//品类名称

        String codedFileName = null;
        OutputStream fOut = null;
        try {
            // 生成提示信息，
            response.setContentType("application/vnd.ms-excel");
            // 进行转码，使其支持中文文件名
            codedFileName = java.net.URLEncoder.encode("H5页面" + timeInterval + "监控统计", "UTF-8");
            response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
            fOut = response.getOutputStream();
            Field[] fields = getFields(headers);
            ex.getHSSFSheet("H5页面首屏时间数据", headers, fields, newList, "yyyy-MM-dd");
            ex.writeToOutput(fOut);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据每列字段名称创建需要导出字段的数组
     *
     * @param headers
     * @return
     */
    public Field[] getFields(String[] headers) {
        Field[] fields = new Field[headers.length];
        PageMonitor t = new PageMonitor();
        try {
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].equals("省份")) {
                    fields[i] = t.getClass().getDeclaredField("province");
                } else if (headers[i].equals("城市")) {
                    fields[i] = t.getClass().getDeclaredField("city");
                } else if (headers[i].equals("运营商")) {
                    fields[i] = t.getClass().getDeclaredField("operators");
                } else if (headers[i].equals("网络制式")) {
                    fields[i] = t.getClass().getDeclaredField("network_type");
                } else if (headers[i].equals("平均时间(s)")) {
                    fields[i] = t.getClass().getDeclaredField("average_time_str");
                } else if (headers[i].equals("访问次数")) {
                    fields[i] = t.getClass().getDeclaredField("visit_times");
                } else if (headers[i].equals("占比")) {
                    fields[i] = t.getClass().getDeclaredField("proportion");
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }

    /**
     * 获取页面上的查询条件
     *
     * @param pageMonitorVO
     * @return
     */
    public PageMonitorVO queryPageMonitorVO(PageMonitorVO pageMonitorVO) {
        //若获取选择时段为null，默认昨日
        if (pageMonitorVO.getChooseTimeVO() == null) {
            Date date0 = new Date();
            SimpleDateFormat formatter1 = new SimpleDateFormat("MM/dd/yyyy");
            Calendar calendar1 = new GregorianCalendar();
            calendar1.setTime(date0);
            calendar1.add(calendar1.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
            Date date1 = calendar1.getTime();
            String dateStr1 = formatter1.format(date1);
            pageMonitorVO.setChooseTimeVO(dateStr1 + " - " + dateStr1);
        }
        //切割字符串，获取开启时间和结束时间
        String[] split = pageMonitorVO.getChooseTimeVO().split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDate = DateTime.parse(split[0].trim() + " 00:00:00", formater).toDate();
        Date endDate = DateTime.parse(split[1].trim() + " 23:59:59", formater).toDate();
        pageMonitorVO.setStart_date(startDate);
        pageMonitorVO.setEnd_date(endDate);

        //echarts的点击事件得到开始时间和结束时间
        String timeInterval = pageMonitorVO.getTimeInterval();
        if ("0s-1s".equals(timeInterval)) {
            pageMonitorVO.setMinTime(0.0);
            pageMonitorVO.setMaxTime(1.0);
        } else if ("1s-2s".equals(timeInterval)) {
            pageMonitorVO.setMinTime(1.0);
            pageMonitorVO.setMaxTime(2.0);
        } else if ("2s-3s".equals(timeInterval)) {
            pageMonitorVO.setMinTime(2.0);
            pageMonitorVO.setMaxTime(3.0);
        } else if ("3s-5s".equals(timeInterval)) {
            pageMonitorVO.setMinTime(3.0);
            pageMonitorVO.setMaxTime(5.0);
        } else if ("5s以上".equals(timeInterval)) {
            pageMonitorVO.setMinTime(5.0);
            pageMonitorVO.setMaxTime(null);
        }
        return pageMonitorVO;
    }


    /**
     * 获取参数选项
     *
     * @return
     */
    public List<SignParamInfo> getSignParamInfoList() {
        List<SignParamInfo> signParamInfoList = new ArrayList<SignParamInfo>();
        signParamInfoList.add(new SignParamInfo("province", "省份", false));
        signParamInfoList.add(new SignParamInfo("city", "城市", false));
        signParamInfoList.add(new SignParamInfo("operators", "运营商", false));
        signParamInfoList.add(new SignParamInfo("network_type", "网络制式", false));
        return signParamInfoList;
    }

    /**
     * 获取参数选项，并且根据数据库记录设置对应的checked属性为true;
     *
     * @param signParam
     * @return
     */
    private List<SignParamInfo> getSignParamInfoList(String signParam) {
        List<SignParamInfo> signParamInfoList = getSignParamInfoList();
        String[] signParams = signParam.split(",");
        for (String s : signParams) {
            for (SignParamInfo signParamInfo : signParamInfoList) {
                if (signParamInfo.getValue().equals(s)) {
                    signParamInfo.setChecked(true);
                }
            }
        }
        return signParamInfoList;
    }


    /**
     * H5首屏查询
     *
     * @param model
     * @param monitorVO
     * @return
     */
    @RequestMapping("firstScreenTimeSearch")
    public String firstScreenTimeSearch(ModelMap model, H5pageMonitorVO h5pageMonitorVO, String province, String city,
                                        String operators, String network_type, Double load_time, String is_lv, String url, String page_type) {
        //接收页面的查询条件
        h5pageMonitorVO.setProvince(province);
        h5pageMonitorVO.setCity(city);
        h5pageMonitorVO.setOperators(operators);
        h5pageMonitorVO.setNetwork_type(network_type);
        h5pageMonitorVO.setIs_lv(is_lv);
        h5pageMonitorVO.setUrl(url);
        h5pageMonitorVO.setLoad_time(load_time);
        h5pageMonitorVO.setPage_type(page_type);//用于模糊和精确查询条件

        //枚举运营商
        CommonStringType[] getOperatorsType = CommonStringType.getOperatorsType();
        List<CommonStringType> operatorsType = Arrays.asList(getOperatorsType);

        //枚举网络制式
        CommonStringType[] getNetworkType = CommonStringType.getNetworkType();
        List<CommonStringType> netWorkType = Arrays.asList(getNetworkType);

        //枚举版本渠道
        CommonStringType[] getIsLvType = CommonStringType.getIsLvType();
        List<CommonStringType> isLvType = Arrays.asList(getIsLvType);

        //页面查询条件
        h5pageMonitorVO = queryMonitorVO(h5pageMonitorVO);
        PageInfo<PageMonitor> page = pageMonitorService.H5pageMonitorSearchPage(h5pageMonitorVO);
        List<PageMonitor> list = page.getList();
        model.addAttribute("H5pageMonitorVO", h5pageMonitorVO);
        model.addAttribute("page", page);
        model.addAttribute("h5pageMonitorList", list);
        model.addAttribute("operatorsList", operatorsType);
        model.addAttribute("netWorkTypeList", netWorkType);
        model.addAttribute("isLvTypeList", isLvType);

        return "application/firstScreenTimeSearch";
    }


    /**
     * 导出首屏查询的信息
     *
     * @param pageMonitorVO
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping("exportSearch")
    public void exportSearchData(H5pageMonitorVO h5pageMonitorVO, String chooseTimeVOExport, String provinceExport, String cityExport,
                                 String operatorsExport, String networkTypeExport, Double loadTimeExport, String isLvExport, String urlExport, String pageTypeExport,
                                 HttpServletResponse response, HttpServletRequest request) throws IOException {
        h5pageMonitorVO.setChooseTimeVO(chooseTimeVOExport);
        h5pageMonitorVO.setProvince(provinceExport);
        h5pageMonitorVO.setCity(cityExport);
        h5pageMonitorVO.setOperators(operatorsExport);
        h5pageMonitorVO.setNetwork_type(networkTypeExport);
        h5pageMonitorVO.setIs_lv(isLvExport);
        h5pageMonitorVO.setUrl(urlExport);
        h5pageMonitorVO.setLoad_time(loadTimeExport);
        h5pageMonitorVO.setPage_type(pageTypeExport);//用于模糊和精确查询条件

        h5pageMonitorVO = queryMonitorVO(h5pageMonitorVO);//页面查询条件

        // H5首屏统计导出-根据查询条件, 查询数据
        List<PageMonitor> listChange = pageMonitorService.H5pageMonitorSearchExport(h5pageMonitorVO);

        if (listChange != null && listChange.size() != 0) {
            // 生成提示信息，
            response.setContentType("application/octet-stream");
            // 进行转码，使其支持中文文件名
            String fileName = java.net.URLEncoder.encode("H5首屏统计", "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".csv");
            BufferedWriter bf = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), "gbk"), 1024);

            String[] headers = new String[]{"省份", "城市", "运营商", "网络制式", "加载时长(s)", "是否H5访问", "链接地址", "时间"};
            Field[] fields = getFieldsSearch(headers);
            ExportCSVUtils<PageMonitor> exportCSVUtils = new ExportCSVUtils<PageMonitor>();
            try {
                logger.info("H5首屏统计导出数据条数:" + listChange.size() + "条");
                exportCSVUtils.exportCSV(headers, fields, listChange, bf, "yyyy-MM-dd HH:mm:ss");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 根据每列字段名称创建需要导出字段的数组
     *
     * @param headers
     * @return
     */
    public Field[] getFieldsSearch(String[] headers) {
        Field[] fields = new Field[headers.length];
        PageMonitor t = new PageMonitor();
        try {
            for (int i = 0; i < headers.length; i++) {
                if (headers[i].equals("省份")) {
                    fields[i] = t.getClass().getDeclaredField("province");
                } else if (headers[i].equals("城市")) {
                    fields[i] = t.getClass().getDeclaredField("city");
                } else if (headers[i].equals("运营商")) {
                    fields[i] = t.getClass().getDeclaredField("operators");
                } else if (headers[i].equals("网络制式")) {
                    fields[i] = t.getClass().getDeclaredField("network_type");
                } else if (headers[i].equals("加载时长(s)")) {
                    fields[i] = t.getClass().getDeclaredField("load_time");
                } else if (headers[i].equals("是否H5访问")) {
                    fields[i] = t.getClass().getDeclaredField("is_lv");
                } else if (headers[i].equals("链接地址")) {
                    fields[i] = t.getClass().getDeclaredField("url");
                } else if (headers[i].equals("时间")) {
                    fields[i] = t.getClass().getDeclaredField("create_date");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fields;
    }


    /**
     * H5首屏统计
     *
     * @param model
     * @return
     */
    @RequestMapping("firstScreenTimeCount")
    public String firstScreenTimeCount(ModelMap model, H5pageMonitorVO h5pageMonitorVO) {
        //取出规则名称
        List<H5Rule> list = pageMonitorService.queryAllRuleTypeName();
        model.addAttribute("ruleTypeList", list);

        return "application/firstScreenTimeCount";
    }


    /**
     * H5首屏查询search请求
     *
     * @param model
     * @return
     */
    @RequestMapping("ajaxfirstScreenTimeCount")
    @ResponseBody
    public Map<String, Object> ajaxfirstScreenTimeCount(ModelMap model, H5pageMonitorVO h5pageMonitorVO, String rule) throws ParseException {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        //页面查询条件
        h5pageMonitorVO = queryMonitorVO(h5pageMonitorVO);
        model.addAttribute("H5pageMonitorVO", h5pageMonitorVO);

        //根据规则名id,查询出规则link_url
        List<H5RuleList> resultUrl = pageMonitorService.queryUrlByRuleId(rule);
        logger.info("查询规则url成功！" + resultUrl.size() + "条Url");

        ArrayList<String> listByOr = new ArrayList<String>();
        ArrayList<String> listByAnd = new ArrayList<String>();
        //循环遍历，规则条件的查询属性or 或者 and
        for (H5RuleList h5RuleList : resultUrl) {
            String linkUrl = h5RuleList.getLinkUrl();
            if ("or".equals(h5RuleList.getConditionName())) {
                listByOr.add(linkUrl);
            } else {
                if (!"0".equals(h5RuleList.getRuleOrder())) {
                    listByAnd.add(linkUrl);
                }
            }

            //根据次序ruleOrder,保存第一个值，用作精确匹配
            if ("0".equals(h5RuleList.getRuleOrder())) {
                h5pageMonitorVO.setIsUrl(h5RuleList.getLinkUrl());
            }
        }

        Map<String, Object> map2 = new HashMap<String, Object>();

        map2.put("listUrlByOr", listByOr);//保存属性为or的
        map2.put("listUrlByAnd", listByAnd);//保存属性为and的

        SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
        map2.put("startDate", dateFormater.format(h5pageMonitorVO.getStartDate()));
        map2.put("endDate", dateFormater.format(h5pageMonitorVO.getEndDate()));
        map2.put("isUrl", h5pageMonitorVO.getIsUrl());
        map2.put("chooseTimeVO", h5pageMonitorVO.getChooseTimeVO());

        H5PageMonitorChannel h5PageMonitorChannel = pageMonitorService.queryTotal(map2);

        if (h5PageMonitorChannel == null) {
            resultMap.put("code", "-1");
            logger.info("渠道版本数据为空");
            return resultMap;
        }

        //耗时时间区间
        String[] timeInterval = new String[]{"0", "1", "2", "3", "4", "5", "6"};
        int size = timeInterval.length;

        Double[] channelDataTotal = new Double[4];
        int channelTotal = 0;
        //根据查询条件,取出各个渠道版本样本量
        List<H5PageMonitorChannel> h5ChannelTotal = pageMonitorService.queryTotalGroupByChannel(map2);
        for (H5PageMonitorChannel h5Channel : h5ChannelTotal) {
            channelTotal = h5Channel.getAmount();
            if ("0".equals(h5Channel.getIsLv())) {
                channelDataTotal[0] = (double) channelTotal;
            } else if ("1".equals(h5Channel.getIsLv())) {
                channelDataTotal[1] = (double) channelTotal;
            } else if ("2".equals(h5Channel.getIsLv())) {
                channelDataTotal[2] = (double) channelTotal;
            } else {
                channelDataTotal[3] = (double) channelTotal;
            }
        }

        //各个渠道的总量
        Double H5total = channelDataTotal[0];
        Double IOStotal = channelDataTotal[1];
        Double Androidtotal = channelDataTotal[2];
        Double NONEtotal = channelDataTotal[3];


        //首屏耗时-渠道版本-根据查询条件，查找满足条件的数据
        List<H5PageMonitorChannel> h5PageChannelList = pageMonitorService.queryH5PageMonitorChannel(map2);
        Double[] H5Data = new Double[size];
        Double[] IOSData = new Double[size];
        Double[] AndroidData = new Double[size];
        Double[] noneChannelData = new Double[size];
        DecimalFormat decimalFormat = new DecimalFormat("#0.00");
        for (H5PageMonitorChannel h5PageChannel : h5PageChannelList) {
            String isLv = h5PageChannel.getIsLv();//渠道版本
            String timeStr = h5PageChannel.getTimeInterval();//时间区间
            if (timeStr != null && isLv != null) {
                int amount = h5PageChannel.getAmount();//访问量

                if (isLv.equals(CommonStringType.H5.getValue())) {
                    String proportionStr = decimalFormat.format((amount / H5total) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    H5Data[Integer.parseInt(timeStr)] = proportion;
                } else if (isLv.equals(CommonStringType.IOS.getValue())) {
                    String proportionStr = decimalFormat.format((amount / IOStotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    IOSData[Integer.parseInt(timeStr)] = proportion;
                } else if (isLv.equals(CommonStringType.Android.getValue())) {
                    String proportionStr = decimalFormat.format((amount / Androidtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    AndroidData[Integer.parseInt(timeStr)] = proportion;
                } else if (isLv.equals(CommonStringType.NONE3.getValue())) {
                    String proportionStr = decimalFormat.format((amount / NONEtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    noneChannelData[Integer.parseInt(timeStr)] = proportion;
                }
            }
        }

        //占比
        resultMap.put("H5Data", H5Data);
        resultMap.put("IOSData", IOSData);
        resultMap.put("AndroidData", AndroidData);
        resultMap.put("noneChannelData", noneChannelData);
        //样本量
        resultMap.put("channelDataTotal", channelDataTotal);


        H5PageMonitorOperator Operator = pageMonitorService.queryTotalByOperators(map2);
        if (Operator == null) {
            resultMap.put("code", "-1");
            logger.info("运营商数据为空");
            return resultMap;
        }

        Double[] operatorDataTotal = new Double[4];
        int operatorTotal = 0;
        //根据查询条件,取出各个运营商样本量
        List<H5PageMonitorOperator> h5OperatorTotal = pageMonitorService.queryTotalGroupByOperator(map2);
        for (H5PageMonitorOperator h5Operator : h5OperatorTotal) {
            operatorTotal = h5Operator.getAmount();
            if (h5Operator.getOperators().equals("CM")) {
                operatorDataTotal[0] = (double) operatorTotal;
            } else if (h5Operator.getOperators().equals("CU")) {
                operatorDataTotal[1] = (double) operatorTotal;
            } else if (h5Operator.getOperators().equals("CT")) {
                operatorDataTotal[2] = (double) operatorTotal;
            } else {
                operatorDataTotal[3] = (double) operatorTotal;
            }
        }

        //首屏耗时-运营商-根据查询条件, 取出运营商总量
        Double CmTotal = operatorDataTotal[0];
        Double CuTotal = operatorDataTotal[1];
        Double CtTotal = operatorDataTotal[2];
        Double NONETotal = operatorDataTotal[3];

        //首屏耗时-运营商-根据查询条件, 查找满足条件的数据
        List<H5PageMonitorOperator> h5PageOperatprslList = pageMonitorService.queryH5PageMonitorOperator(map2);
        Double[] cuData = new Double[size];
        Double[] ctData = new Double[size];
        Double[] cmData = new Double[size];
        Double[] noneOperatorsData = new Double[size];
        for (H5PageMonitorOperator h5PageOperator : h5PageOperatprslList) {
            String operator = h5PageOperator.getOperators();//运营商(中国移动-CM、中国联通-CU、中国电信-CT、其他-NONE)
            String timeStr = h5PageOperator.getTimeInterval();//时间区间
            if (timeStr != null && operator != null) {
                int amount = h5PageOperator.getAmount();//访问量
                if (operator.equals(CommonStringType.CU.getValue())) {
                    String proportionStr = decimalFormat.format((amount / CuTotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    cuData[Integer.parseInt(timeStr)] = proportion;
                } else if (operator.equals(CommonStringType.CT.getValue())) {
                    String proportionStr = decimalFormat.format((amount / CtTotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    ctData[Integer.parseInt(timeStr)] = proportion;
                } else if (operator.equals(CommonStringType.CM.getValue())) {
                    String proportionStr = decimalFormat.format((amount / CmTotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    cmData[Integer.parseInt(timeStr)] = proportion;
                } else if (operator.equals(CommonStringType.NONE1.getValue())) {
                    String proportionStr = decimalFormat.format((amount / NONETotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    noneOperatorsData[Integer.parseInt(timeStr)] = proportion;
                }
            }

        }

        //占比
        resultMap.put("cuData", cuData);
        resultMap.put("ctData", ctData);
        resultMap.put("cmData", cmData);
        resultMap.put("noneOperatorsData", noneOperatorsData);
        //样本量
        resultMap.put("operatorDataTotal", operatorDataTotal);


        H5PageMonitorNetworkType NetworkType = pageMonitorService.queryTotalByNetworkType(map2);
        if (NetworkType == null) {
            resultMap.put("code", "-1");
            logger.info("网络制式数据为空");
            return resultMap;
        }

        Double[] netWorkTypeDataTotal = new Double[5];
        int netWorkTypeTotal = 0;
        //根据查询条件,取出各个网络制式本样本量
        List<H5PageMonitorNetworkType> h5NetworkTypeTotal = pageMonitorService.queryTotalGroupByNetworkType(map2);
        for (H5PageMonitorNetworkType h5NetworkType : h5NetworkTypeTotal) {
            netWorkTypeTotal = h5NetworkType.getAmount();
            if ("2G".equals(h5NetworkType.getNetworkType())) {
                netWorkTypeDataTotal[0] = (double) netWorkTypeTotal;
            } else if ("3G".equals(h5NetworkType.getNetworkType())) {
                netWorkTypeDataTotal[1] = (double) netWorkTypeTotal;
            } else if ("4G".equals(h5NetworkType.getNetworkType())) {
                netWorkTypeDataTotal[2] = (double) netWorkTypeTotal;
            } else if ("WIFI".equals(h5NetworkType.getNetworkType())) {
                netWorkTypeDataTotal[3] = (double) netWorkTypeTotal;
            } else {
                netWorkTypeDataTotal[4] = (double) netWorkTypeTotal;
            }
        }

        //首屏耗时-网络制式-根据查询条件, 取出网络制式总量
        Double TwoGtotal = netWorkTypeDataTotal[0];
        Double ThreeGtotal = netWorkTypeDataTotal[1];
        Double FourGtotal = netWorkTypeDataTotal[2];
        Double WIFIGtotal = netWorkTypeDataTotal[3];
        Double NONEGtotal = netWorkTypeDataTotal[4];


        //首屏耗时-网络制式-根据查询条件, 查找满足条件的数据
        List<H5PageMonitorNetworkType> h5PageNetworkTypeprslList = pageMonitorService.queryH5PageMonitorNetworkType(map2);

        Double[] twoGData = new Double[size];
        Double[] threeGData = new Double[size];
        Double[] fourGData = new Double[size];
        Double[] wifiData = new Double[size];
        Double[] noneNetWorkTypeData = new Double[size];
        for (H5PageMonitorNetworkType h5PageNetworkType : h5PageNetworkTypeprslList) {
            String netWorkType = h5PageNetworkType.getNetworkType();//网络制式
            String timeStr = h5PageNetworkType.getTimeInterval();//时间区间
            if (timeStr != null && netWorkType != null) {
                int amount = h5PageNetworkType.getAmount();//访问量
                if (netWorkType.equals(CommonStringType.TWO_G.getValue())) {
                    String proportionStr = decimalFormat.format((amount / TwoGtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    twoGData[Integer.parseInt(timeStr)] = proportion;
                } else if (netWorkType.equals(CommonStringType.THREE_G.getValue())) {
                    String proportionStr = decimalFormat.format((amount / ThreeGtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    threeGData[Integer.parseInt(timeStr)] = proportion;
                } else if (netWorkType.equals(CommonStringType.FOUR_G.getValue())) {
                    String proportionStr = decimalFormat.format((amount / FourGtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    fourGData[Integer.parseInt(timeStr)] = proportion;
                } else if (netWorkType.equals(CommonStringType.WIFI.getValue())) {
                    String proportionStr = decimalFormat.format((amount / WIFIGtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    wifiData[Integer.parseInt(timeStr)] = proportion;
                } else if (netWorkType.equals(CommonStringType.NONE2.getValue())) {
                    String proportionStr = decimalFormat.format((amount / NONEGtotal) * 100);
                    Double proportion = Double.parseDouble(proportionStr);
                    noneNetWorkTypeData[Integer.parseInt(timeStr)] = proportion;
                }
            }
        }


        //占比
        resultMap.put("twoGData", twoGData);
        resultMap.put("threeGData", threeGData);
        resultMap.put("fourGData", fourGData);
        resultMap.put("wifiData", wifiData);
        resultMap.put("noneNetWorkTypeData", noneNetWorkTypeData);
        //样本量
        resultMap.put("netWorkTypeDataTotal", netWorkTypeDataTotal);


        //首屏耗时-地域-根据查询条件, 查找满足条件的数据
        List<H5PageMonitorRegion> h5PageMonitorRegionList = pageMonitorService.queryRegionProvinceList(map2);

        int regionCount = h5PageMonitorRegionList.size();
        String[] monitorRegionProvince = new String[regionCount];
        Double[] avgTimeDate = new Double[regionCount];
        Double[] amountDate = new Double[regionCount];
        for (int i = 0; i < regionCount; i++) {
            monitorRegionProvince[i] = h5PageMonitorRegionList.get(i).getProvince();
            avgTimeDate[i] = h5PageMonitorRegionList.get(i).getLoadTime();
            int amountNum = h5PageMonitorRegionList.get(i).getAmount();
            amountDate[i] = (double) amountNum;
        }

        resultMap.put("province", monitorRegionProvince);
        resultMap.put("avgTimeDate", avgTimeDate);
        resultMap.put("amountDate", amountDate);
        resultMap.put("code", "1");

        return resultMap;
    }


    /**
     * 跳转到添加规则
     *
     * @param model
     * @return
     */
    @RequestMapping("add")
    public String firstScreenTimeCountAdd(ModelMap model) {


        //取出规则名称
        List<H5Rule> list = pageMonitorService.queryAllRuleTypeName();
        model.addAttribute("ruleTypeList", list);
        return "application/firstScreenTimeCountAdd";
    }


    /**
     * 跳转到维护规则
     *
     * @param model
     * @return
     */
    @RequestMapping("maintenance")
    public String firstScreenTimeCountMaintenance(ModelMap model, H5RuleVO h5RuleVO, String name) {

        h5RuleVO.setName(name);
        PageInfo<H5Rule> page = pageMonitorService.H5pageMonitorMaintenancePage(h5RuleVO);
        List<H5Rule> list = page.getList();
        model.addAttribute("H5RuleVO", h5RuleVO);
        model.addAttribute("page", page);
        model.addAttribute("maintenanceList", list);

        return "application/firstScreenTimeMaintenance";
    }


    /**
     * 维护规则-编辑, id为h5_rule_type表的id和h5_rule_url表的rule_id, ruleId为h5_rule_url的id
     *
     * @param model
     * @param h5RuleVO
     * @return
     */
    @RequestMapping("ruleEdit")
    public String firstScreenTimeCountEdit(ModelMap model, String id, String ruleId) {

        H5Rule h5RuleList = pageMonitorService.queryH5RuleListById(ruleId);
        model.addAttribute("H5Rule", h5RuleList);

        return "application/firstScreenTimeCountEdit";
    }

    /**
     * 保存编辑的规则
     *
     * @param model
     * @return
     */
    @RequestMapping("saveEditRule")
    public String firstScreenTimeCountSaveEdit(ModelMap model, H5Rule h5Ruleform) {

        //取出规则名称
        List<H5Rule> list = pageMonitorService.queryAllRuleTypeName();
        model.addAttribute("ruleTypeList", list);

        pageMonitorService.saveEditRule(h5Ruleform);
        return "application/firstScreenTimeCount";
    }

    /**
     * 维护规则-删除, id为h5_rule_type表的id和h5_rule_url表的rule_id, ruleId为h5_rule_url的id
     *
     * @param model
     * @param h5RuleVO
     * @return
     */
    @RequestMapping("ruleDelete")
    @ResponseBody
    public Map<String, Object> firstScreenTimeCountDelete(String id, String ruleId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();

        List<H5RuleList> h5RuleList = pageMonitorService.queryUrlByRuleId(id);
        if (h5RuleList.size() > 1) {
            pageMonitorService.deleteRuleUrl(ruleId);
            logger.info("规则配置Url删除成功！");
        } else {
            pageMonitorService.deleteRuleType(id);
            logger.info("规则类型删除成功！");
            pageMonitorService.deleteRuleUrl(ruleId);
            logger.info("规则配置Url删除成功！");
        }
        resultMap.put("code", 1);

        return resultMap;
    }


    /**
     * 保存添加的规则
     *
     * @param model
     * @return
     */
    @RequestMapping("saveRule")
    public String firstScreenTimeCountSave(ModelMap model, H5Rule h5Ruleform) {
        String rules = StringEscapeUtils.unescapeXml(h5Ruleform.getRules());
        JSONObject jsonRules = JSONObject.parseObject(rules);

        pageMonitorService.saveH5Ruleform(h5Ruleform, jsonRules);
        logger.info("规则添加成功");

        //取出规则名称
        List<H5Rule> list = pageMonitorService.queryAllRuleTypeName();
        model.addAttribute("ruleTypeList", list);

        return "application/firstScreenTimeCount";
    }


    /**
     * 页面查询条件
     *
     * @param h5pageMonitorVO
     * @return
     */
    public H5pageMonitorVO queryMonitorVO(H5pageMonitorVO h5pageMonitorVO) {
        if (h5pageMonitorVO.getChooseTimeVO() == null) {
            //页面打开默认时间段
            Date date = new Date();
            String startDateStr = DateUtil.getStrDayOfMonth(date, -30, "MM/dd/yyyy");
            String endDateStr = DateUtil.getStrDayOfMonth(date, -1, "MM/dd/yyyy");
            h5pageMonitorVO.setChooseTimeVO(startDateStr + " - " + endDateStr);
        }

        //切割字符串，获取开启时间和结束时间
        String[] split = h5pageMonitorVO.getChooseTimeVO().split("-");
        DateTimeFormatter formater = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
        Date startDate = DateTime.parse(split[0].trim() + " 00:00:00", formater).toDate();
        Date endDate = DateTime.parse(split[1].trim() + " 23:59:59", formater).toDate();
        h5pageMonitorVO.setStartDate(startDate);
        h5pageMonitorVO.setEndDate(endDate);

        String[] strDate = DateUtil.getBetweenTime(startDate, endDate, "yyyy-MM-dd");
        h5pageMonitorVO.setDateInterval(strDate);
        return h5pageMonitorVO;
    }

}
